package com.lnt.mq.rabbitmq.workqueue;

import com.lnt.mq.rabbitmq.util.RabbitConstant;
import com.lnt.mq.rabbitmq.util.RabbitUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * 短信发送系统1
 * 扮演接收者行为
 */
public class SMSSendSystem1 {

    public static void main(String[] args) throws IOException {
        Connection connection = RabbitUtil.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueDeclare(RabbitConstant.QUEUR_SMS, false, false, false, null);
        // 如果未设置basicQos(), MQ会自动将所有的请求平均发给所有的消费者
        // basicQos的作用:MQ不再对消费者一次性发送多个请求，而是等待消费者处理完一个，即ack签收完一个，再从队列中取一个
        channel.basicQos(1);
        channel.basicConsume(RabbitConstant.QUEUR_SMS, false, new DefaultConsumer(channel){

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String jsonString = new String(body);
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("SMSSystem1--短信发送成功" + jsonString);
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}
